package com.joycessh.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.joycessh.PO.user.UserPO;
import com.joycessh.dao.HibernateServiceProvider;
import com.joycessh.dao.IUserDao;

public class UserDaoImpl implements IUserDao {
	
	HibernateServiceProvider hbp = new HibernateServiceProvider();

	@Override
	public boolean saveUser(UserPO userpo) throws HibernateException {
		// TODO Auto-generated method stub
		
		boolean flag = false;
		Session session = hbp.getSession();	   
		Transaction t = null;
		try 
		{		
		    t = session.beginTransaction();
		    //如果在MonkeyPO中用了级联，则仅保存monkeypo即可
		    //	       session.save(teampo);          //如果没有级联，必须先保存team
		    session.save(userpo);    //后保存monkey
		    t.commit();
		    flag = true;
		} 
		catch (HibernateException he) 
		{			
		   if (t != null) 
		   {
		       t.rollback();
		       he.printStackTrace();
		   }
		   flag = false;
		   throw he;
		}
		finally
			{
			    session.close();
			}
		return flag;	
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean checkUser(String userId, String password) throws HibernateException {
		// TODO Auto-generated method stub
		Session session = hbp.getSession();   //创建一个会话
		List<UserPO> result = new ArrayList<UserPO>();
	    Transaction tx = null;	 
	    boolean flag = false;
	    try
	    {		
	    	String hql = "from UserPO as m where m.userId = ? and m.password = ?";	   //使用占位符问号
	    	tx = session.beginTransaction();   //开始一个事务
	    	Query query = session.createQuery(hql);
	    	query.setString(0,userId);
	    	query.setString(1, password);
	    	result = query.list();   //结果集
	    	tx.commit(); //提交事务
	    }catch (HibernateException he) 
	    {
	      if (tx != null) {
	         tx.rollback();
	      }
	      throw he;
	    } finally 
	    {
	       session.close();
	    }
	    
	    if(result.iterator().hasNext()) {
	    	flag = true;
	    }else {
	    	flag = false;
	    }
	    return flag;
	}

}
